﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using SmsVotes.DataAccess;

namespace SmsVotes.SmsVoting
{
    /// <summary>
    /// Контрол создания вопроса
    /// </summary>
    public partial class Question : CommandControl
    {
        /// <summary>
        /// Текущий вопрос
        /// </summary>
        private DataAccess.Question CurrentQuestion
        {
            get
            {
                int id = (int)ViewState["CurrentQuestionID"];
                if (Request.QueryString["vid"] != null)
                {
                    DataAccess.Vote vote = VoteManager.GetByID(int.Parse(Request.QueryString["vid"]));
                    vote.Questions.SmartLoad(vote);
                    return (from item in vote.Questions
                            where item.ID == id
                            select item).FirstOrDefault();
                }
                else
                    return QuestionManager.GetByID(id);
            }
            set
            {
                ViewState["CurrentQuestionID"] = value.ID;
            }
        }

        /// <summary>
        /// Текущий ответ
        /// </summary>
        private DataAccess.Answer CurrentAnswer
        {
            get
            {
                if (ViewState["CurrentAnswerGUID"] == null)
                    return null;
                return (from a in CurrentQuestion.Answers where a.Guid.Equals((Guid)ViewState["CurrentAnswerGUID"]) select a).First();
            }
            set
            {
                if (value != null)
                    ViewState["CurrentAnswerGUID"] = value.Guid;
                else
                    ViewState["CurrentAnswerGUID"] = null;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateCharts();

                if (Command == COMMAND_QUESTIONEDIT)
                {
                    int questionID = int.Parse(Request.QueryString["qid"]);
                    this.CurrentQuestion = QuestionManager.GetByID(questionID);
                    tbQuestion.Text = this.CurrentQuestion.Name;
                    tbDuration.Text = CurrentQuestion.ChangeTime.ToString();
                    ddlDiagramType.SelectedIndex = ddlDiagramType.Items.IndexOf(ddlDiagramType.Items.FindByValue(CurrentQuestion.Chart.ID.ToString()));
                    lbtnCreateNextQuestion.Text = "Сохранить";
                    lbtnRedirectToSort.Text = "Отменить";
                    BindAnswers();
                }
                if (Command == COMMAND_QUESTIONCREATE)
                {
                    DataAccess.Question question = new DataAccess.Question();
                    DataAccess.Vote vote = VoteManager.GetByID(int.Parse(Request.QueryString["vid"]));
                    vote.Questions.SmartLoad(vote);
                    vote.Questions.Add(question);
                    CurrentQuestion = question;
                }
            }
        }

        private void PopulateCharts()
        {
            ddlDiagramType.DataSource = QuestionManager.GetAllCharts();
            ddlDiagramType.DataTextField = "Name";
            ddlDiagramType.DataValueField = "ID";
            ddlDiagramType.DataBind();
        }

        protected void lbtnCreateNextQuestion_Click(object sender, EventArgs e)
        {
            CurrentQuestion.Name = tbQuestion.Text;
            CurrentQuestion.Chart = (QuestionManager.GetChartByID(int.Parse(ddlDiagramType.SelectedValue)));
            CurrentQuestion.ChangeTime = int.Parse(tbDuration.Text);

            if (Command.Equals(COMMAND_QUESTIONEDIT, StringComparison.InvariantCultureIgnoreCase))
            {
                QuestionManager.Save();
                Response.Redirect(string.Format("smsvoting.aspx?cmd={0}&vid={1}", COMMAND_VOTEEDIT, CurrentQuestion.Vote.ID), true);
            }
            if (Command.Equals(COMMAND_QUESTIONCREATE, StringComparison.InvariantCultureIgnoreCase))
            {
                QuestionManager.Save();
                Response.Redirect(this.Request.RawUrl, true);
            }
        }

        protected void lbtnRedirectToSort_Click(object sender, EventArgs e)
        {
            // сохраняем вопрос - отключено
            // переход на страницу сортировки вопросов

            if (Command == "createquestion")
            {
                //string cmd = Request.QueryString["cmd"];
                //CurrentQuestion.Name = tbQuestion.Text;
                //CurrentQuestion.ChangeTime = int.Parse(tbDuration.Text);
                //CurrentQuestion.Chart = QuestionManager.GetChartByID(int.Parse(ddlDiagramType.SelectedValue));
                //QuestionManager.Save();
                QuestionManager.Reset();
                Response.Redirect("smsvoting.aspx?cmd=editvote&vid=" + Request.QueryString["vid"], true);
            }
            else
            {
                QuestionManager.Reset();
                Response.Redirect("smsvoting.aspx?cmd=editvote&vid=" + CurrentQuestion.Vote.ID, true);
            }

        }

        protected void lbtnSaveAnswer_Click(object sender, EventArgs e)
        {
            // сохраняем ответ
            if (CurrentAnswer == null)
            {
                var answer = new Answer()
                {
                    Name = tbAnswer.Text
                };

                CurrentQuestion.Answers.Add(answer);
            }
            else
                CurrentAnswer.Name = tbAnswer.Text;


            BindAnswers();
        }

        protected void lvAnswers_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName.Equals(COMMAND_ANSWEREDIT, StringComparison.InvariantCultureIgnoreCase))
            {
                CurrentAnswer = (from item in CurrentQuestion.Answers
                                 where item.Guid.ToString() == e.CommandArgument.ToString()
                                 select item).First();

                tbAnswer.Text = CurrentAnswer.Name;
                mpeAnswer.Show();
            }
            else if (e.CommandName.Equals(COMMAND_ANSWERDELETE, StringComparison.InvariantCultureIgnoreCase))
            {
                var answer = (from item in CurrentQuestion.Answers
                              where item.Guid.ToString() == e.CommandArgument.ToString()
                              select item).First();

                answer.AnswerStates.SmartLoad(answer);
                if (answer.AnswerStates.Count == 0)
                    QuestionManager.Delete(answer);
                else
                {
                    // TODO: Кинуть exception
                    ;
                }

                BindAnswers();
            }
        }

        private void BindAnswers()
        {
            CurrentQuestion.Answers.SmartLoad(CurrentQuestion);
            lvAnswers.DataSource = CurrentQuestion.Answers;
            lvAnswers.DataBind();
            hfAnswersCount.Value = CurrentQuestion.Answers.Count.ToString();
        }

        protected void lbtnCreateAnswer_Click(object sender, EventArgs e)
        {
            CurrentAnswer = null;
            tbAnswer.Text = "";
            mpeAnswer.Show();
        }

    }
}